<template>
  <div class="qr-code-management">
    <el-card>
      <div slot="header" class="clearfix">
        <span class="page-title"><i class="el-icon-tickets"></i> 聚合码管理</span>
        <div class="header-actions">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="showGenerateDialog">
            生成聚合码
          </el-button>
        </div>
      </div>

      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="商家名称">
            <el-input v-model="searchForm.merchantName" placeholder="请输入商家名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="searchForm.startTime"
              type="date"
              placeholder="选择开始时间"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="searchForm.endTime"
              type="date"
              placeholder="选择结束时间"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <configurable-table
        :columns="tableColumns"
        :data="tableData"
        :loading="loading"
        :show-pagination="true"
        :current-page.sync="pagination.current"
        :page-size.sync="pagination.size"
        :pagination-total="pagination.total"
        index-label="序号"
        index-width="80"
        @page-change="handlePageChange"
        border>
        <!-- 聚合码列 -->
        <template #qrCodeUrl="{ row }">
          <div v-if="row.qrCodeUrl" class="qr-code-preview">
            <el-image
              :src="getFullQrCodeUrl(row.qrCodeUrl)"
              style="width: 60px; height: 60px;"
              fit="cover"
              :preview-src-list="[getFullQrCodeUrl(row.qrCodeUrl)]"
              @error="handleImageError">
              <div slot="error" class="image-error">
                <i class="el-icon-picture-outline"></i>
                <div>加载失败</div>
              </div>
            </el-image>
          </div>
          <span v-else class="no-qr">未生成</span>
        </template>

        <!-- 扫码次数列 -->
        <template #scanCount="{ row }">
          <span>{{ row.scanCount || 0 }}</span>
        </template>

        <!-- 最后扫码时间列 -->
        <template #lastScanTime="{ row }">
          <span>{{ row.lastScanTime || '-' }}</span>
        </template>

        <!-- 状态列 -->
        <template #status="{ row }">
          <el-tag :type="getStatusTag(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>

        <!-- 操作列 -->
        <template #actions="{ row }">
          <el-button size="mini" icon="el-icon-view" @click="handleView(row)">查看</el-button>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-refresh"
            @click="handleRegenerate(row)">
            重新生成
          </el-button>
          <el-button
            size="mini"
            type="success"
            icon="el-icon-download"
            @click="handleDownload(row)">
            下载
          </el-button>
        </template>
      </configurable-table>
    </el-card>

    <!-- 生成聚合码对话框 -->
    <el-dialog title="生成聚合码" :visible.sync="generateDialogVisible" width="600px" :close-on-click-modal="false" custom-class="action-dialog">
      <el-form :model="generateForm" :rules="generateRules" ref="generateForm" label-width="120px">
        <el-form-item label="选择商家" prop="merchantId">
          <el-select v-model="generateForm.merchantId" placeholder="请选择商家" style="width: 100%" @change="handleMerchantChange">
            <el-option
              v-for="merchant in merchantList"
              :key="merchant.id"
              :label="merchant.name"
              :value="merchant.id">
              <span style="float: left">{{ merchant.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ merchant.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商家信息" v-if="selectedMerchant">
          <div class="merchant-info">
            <p><strong>商家名称：</strong>{{ selectedMerchant.name }}</p>
            <p><strong>联系电话：</strong>{{ selectedMerchant.phone }}</p>
            <p><strong>商家地址：</strong>{{ selectedMerchant.address }}</p>
          </div>
        </el-form-item>
        <el-form-item label="聚合码功能">
          <div class="qr-functions">
            <div class="function-item">
              <i class="el-icon-download"></i>
              <span>未下载app的用户扫描可下载app</span>
            </div>
            <div class="function-item">
              <i class="el-icon-view"></i>
              <span>用户使用app扫描可查看商家商品</span>
            </div>
            <div class="function-item">
              <i class="el-icon-shopping-cart-2"></i>
              <span>扫描二维码可用于结账</span>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="generateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleGenerateSubmit" :loading="generateLoading">生成聚合码</el-button>
      </div>
    </el-dialog>

    <!-- 查看聚合码详情对话框 -->
    <el-dialog title="聚合码详情" :visible.sync="detailDialogVisible" width="500px" custom-class="view-dialog">
      <div class="qr-detail" v-if="detailData">
        <div class="qr-code-display">
          <div class="qr-code-image">
            <el-image
              v-if="detailData.qrCodeUrl"
              :src="getFullQrCodeUrl(detailData.qrCodeUrl)"
              style="width: 200px; height: 200px;"
              fit="cover">
            </el-image>
            <div v-else class="no-qr-large">
              <i class="el-icon-picture-outline"></i>
              <p>未生成聚合码</p>
            </div>
          </div>
          <div class="qr-code-info">
            <h4>聚合码功能说明</h4>
            <ul>
              <li>未下载app的用户扫描可下载app</li>
              <li>用户使用app扫描可查看商家商品</li>
              <li>扫描二维码可用于结账</li>
            </ul>
          </div>
        </div>

        <div class="merchant-detail">
          <h4>商家信息</h4>
          <div class="detail-item">
            <label>商家名称：</label>
            <span>{{ detailData.merchantName || '无' }}</span>
          </div>
          <div class="detail-item">
            <label>联系电话：</label>
            <span>{{ detailData.merchantPhone || '无' }}</span>
          </div>
          <div class="detail-item">
            <label>商家地址：</label>
            <span>{{ detailData.merchantAddress || '无' }}</span>
          </div>
          <div class="detail-item">
            <label>生成时间：</label>
            <span>{{ detailData.createTime || '无' }}</span>
          </div>
          <div class="detail-item">
            <label>状态：</label>
            <el-tag :type="getStatusTag(detailData.status)">
              {{ getStatusText(detailData.status) }}
            </el-tag>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleDownload(detailData)" v-if="detailData && detailData.qrCodeUrl">下载聚合码</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMerchantPage, generateQrCode, generateDownloadQrCode, getQrCodePage, getQrCodeDetail } from '@/api/aggregation'
import ConfigurableTable from '@/components/ConfigurableTable'

export default {
  name: 'QrCodeManagement',
  components: {
    ConfigurableTable
  },
  data() {
    return {
      loading: false,
      generateLoading: false,
      searchForm: {
        merchantName: '',
        startTime: '',
        endTime: ''
      },
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 表格列配置
      tableColumns: [
        { prop: 'id', label: 'ID', minWidth: 80, align: 'center' },
        { prop: 'merchantName', label: '商家名称', minWidth: 150, align: 'center', showOverflowTooltip: true },
        { prop: 'merchantPhone', label: '商家电话', minWidth: 130, align: 'center' },
        { prop: 'qrCodeUrl', label: '聚合码', minWidth: 120, align: 'center', slot: 'qrCodeUrl' },
        { prop: 'createTime', label: '生成时间', minWidth: 180, align: 'center', showOverflowTooltip: true },
        { prop: 'scanCount', label: '扫码次数', minWidth: 100, align: 'center', slot: 'scanCount' },
        { prop: 'lastScanTime', label: '最后扫码时间', minWidth: 180, align: 'center', showOverflowTooltip: true, slot: 'lastScanTime' },
        { prop: 'status', label: '状态', minWidth: 100, align: 'center', slot: 'status' },
        { prop: 'actions', label: '操作', minWidth: 300, align: 'center', fixed: 'right', slot: 'actions' }
      ],
      // 生成聚合码对话框
      generateDialogVisible: false,
      generateForm: {
        merchantId: null
      },
      generateRules: {
        merchantId: [
          { required: true, message: '请选择商家', trigger: 'change' }
        ]
      },
      merchantList: [],
      selectedMerchant: null,
      // 详情对话框
      detailDialogVisible: false,
      detailData: null
    }
  },
  mounted() {
    this.loadData()
    this.loadMerchantList()
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        const params = {
          pageIndex: this.pagination.current,
          pageSize: this.pagination.size,
          merchantName: this.searchForm.merchantName,
          startTime: this.searchForm.startTime,
          endTime: this.searchForm.endTime
        }

        const response = await getQrCodePage(params)

        if (response.code === 0) {
          this.tableData = response.data.list || []
          this.pagination.total = response.data.total || 0
        } else {
          this.tableData = []
          this.pagination.total = 0
        }
      } catch (error) {
        Logger.error('加载聚合码数据失败:', error)
        this.$message.error('加载数据失败')
        this.tableData = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },

    async loadMerchantList() {
      try {
        const params = {
          pageIndex: 1,
          pageSize: 1000,
          type: 3 // 商家类型
        }
        const response = await getMerchantPage(params)
        if (response.code === 0) {
          this.merchantList = response.data.list || []
        }
      } catch (error) {
        Logger.error('加载商家列表失败:', error)
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadData()
    },

    // 重置
    handleReset() {
      this.searchForm = {
        merchantName: '',
        startTime: '',
        endTime: ''
      }
      this.pagination.current = 1
      this.loadData()
    },

    // 查看详情
    async handleView(row) {
      try {
        const response = await getQrCodeDetail(row.id)
        if (response.code === 0) {
          this.detailData = response.data
          this.detailDialogVisible = true
        } else {
          this.$message.error('获取详情失败')
        }
      } catch (error) {
        Logger.error('获取聚合码详情失败:', error)
        this.$message.error('获取详情失败')
      }
    },

    // 重新生成聚合码
    async handleRegenerate(row) {
      try {
        await this.$confirm('确定要重新生成该商家的聚合码吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        this.generateLoading = true
        const response = await generateQrCode(row.merchantId)

        if (response.code === 0) {
          this.$message.success('聚合码重新生成成功')
          this.loadData()
        } else {
          this.$message.error('生成失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          Logger.error('重新生成聚合码失败:', error)
          this.$message.error('生成失败')
        }
      } finally {
        this.generateLoading = false
      }
    },

    // 下载聚合码
    handleDownload(row) {
      if (!row.qrCodeUrl) {
        this.$message.warning('该商家尚未生成聚合码')
        return
      }

      // 创建下载链接
      const link = document.createElement('a')
      link.href = this.getFullQrCodeUrl(row.qrCodeUrl)
      link.download = `${row.merchantName}_聚合码.png`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

      this.$message.success('聚合码下载成功')
    },

    // 显示生成对话框
    showGenerateDialog() {
      this.generateForm.merchantId = null
      this.selectedMerchant = null
      this.generateDialogVisible = true
    },

    // 商家选择变化
    handleMerchantChange(merchantId) {
      this.selectedMerchant = this.merchantList.find(m => m.id === merchantId)
    },

    // 提交生成聚合码
    async handleGenerateSubmit() {
      try {
        await this.$refs.generateForm.validate()
        this.generateLoading = true

        const response = await generateQrCode(this.generateForm.merchantId)

        if (response.code === 0) {
          this.$message.success('聚合码生成成功')
          this.generateDialogVisible = false
          this.loadData()
        } else {
          this.$message.error('生成失败')
        }
      } catch (error) {
        Logger.error('生成聚合码失败:', error)
        this.$message.error('生成失败')
      } finally {
        this.generateLoading = false
      }
    },

    // 获取状态标签类型
    getStatusTag(status) {
      const statusMap = {
        0: 'info',     // 未生成
        1: 'success'   // 已生成
      }
      return statusMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '未生成',
        1: '已生成'
      }
      return statusMap[status] || '未知'
    },

    // 获取完整的二维码URL
    getFullQrCodeUrl(qrCodeUrl) {
      if (!qrCodeUrl) return ''
      // 如果已经是完整URL，直接返回
      if (qrCodeUrl.startsWith('http')) {
        return qrCodeUrl
      }
      // 使用相对路径，通过代理访问图片
      return `/profile/${qrCodeUrl}`
    },

    // 处理图片加载错误
    handleImageError(event) {
      Logger.error('图片加载失败:', event.target.src)
      // 可以在这里添加重试逻辑或显示默认图片
    },

    // 分页处理
    handlePageChange({ currentPage, pageSize }) {
      this.pagination.current = currentPage
      this.pagination.size = pageSize
      this.loadData()
    }
  }
}
</script>

<style scoped>
.qr-code-management {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

/* 二维码预览样式 */
.qr-code-preview {
  display: flex;
  justify-content: center;
  align-items: center;
}

.no-qr {
  color: #909399;
  font-size: 12px;
}

.no-qr-large {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #c0c4cc;
  font-size: 16px;
}

.no-qr-large i {
  font-size: 48px;
  margin-bottom: 10px;
}

/* 商家信息样式 */
.merchant-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.merchant-info p {
  margin: 5px 0;
  color: #606266;
}

/* 聚合码功能说明样式 */
.qr-functions {
  background: #f0f9ff;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #b3d8ff;
}

.function-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  color: #409eff;
}

.function-item:last-child {
  margin-bottom: 0;
}

.function-item i {
  margin-right: 8px;
  font-size: 16px;
}

/* 聚合码详情样式 */
.qr-detail {
  padding: 20px 0;
}

.qr-code-display {
  text-align: center;
  margin-bottom: 30px;
}

.qr-code-image {
  margin-bottom: 20px;
}

.qr-code-info {
  background: #f0f9ff;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #b3d8ff;
}

.qr-code-info h4 {
  margin: 0 0 10px 0;
  color: #409eff;
}

.qr-code-info ul {
  margin: 0;
  padding-left: 20px;
  color: #606266;
}

.qr-code-info li {
  margin-bottom: 5px;
}

.merchant-detail h4 {
  margin: 0 0 15px 0;
  color: #303133;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 10px;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
  align-items: flex-start;
}

.detail-item label {
  font-weight: bold;
  min-width: 80px;
  color: #606266;
}

.detail-item span {
  flex: 1;
  color: #303133;
}

/* 表格样式优化 */
::v-deep .configurable-table {
  .el-table {
    border-radius: 6px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .el-table th {
    background: #f5f7fa;
    color: #606266;
    font-weight: 600;
  }
}

/* 页面标题样式 */
.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

/* 卡片头部样式 */
.el-card__header {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #dee2e6;
  border-radius: 8px 8px 0 0;
  padding: 20px 24px;
}

.el-card__header .clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-card__header .page-title {
  color: #2c3e50;
  font-size: 22px;
  font-weight: 700;
  letter-spacing: 0.5px;
}

/* 对话框底部样式已移至公共样式 dialog.scss */

/* 响应式设计 */
@media (max-width: 768px) {
  .el-card__header .clearfix {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-actions {
    margin-top: 10px;
  }
}
</style>
